package cn.chenddcoder.operator;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class MessageOperator {
    private final Map<String, WebSocketSession> sessions = new HashMap<>();
    public void add(String userId,WebSocketSession session){
        sessions.put(userId,session);
    }
    public void remove(String userId){
        if (ObjectUtil.isEmpty(userId)){
            return;
        }
        sessions.remove(userId);
    }

    public void send(String userId, String message) throws IOException {
        WebSocketSession webSocketSession = sessions.get(userId);
        if (webSocketSession!=null){
            webSocketSession.sendMessage(new TextMessage(message));
        }
    }
}
